package top.as.sean.common.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 用于手动从容器获取数据
 *
 * @author: ArchieSean
 * @create: 2022/11/6
 */
public class SpringContextUtil implements ApplicationContextAware {
    /**
     * spring容器
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取spring容器
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 用于从容器中获取bean
     *
     * @param name bean名称
     * @return obj
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 从容器中获取指定bean
     *
     * @param clazz 字节码
     * @param <T>   泛型
     * @return obj
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}
